#!/usr/bin/php

<?php

	function Functions($infile){
		
		$done = false;
		$output = "";
		$line = "";
		
		while(!$done){
			$output .= $line;
			
			$line = fgets($infile);
			
			$linedata = explode(" ", $line);
        
			if($linedata[0] == "//^^^")
				$done = true;
		}
		
		return $output;
		
	}

	function InstructionMacro($infile){

		$parenBalance = 1;
		$output = "";
		
		$line = fgets($infile);
		
		$linedata = explode(" ", $line);
		
		$linedata2 = explode("(", $linedata[1]);
		
		$opname = $linedata2[0];
		
		$output = "//". strtoupper($opname) . "\n" . "#define " . $opname . "(CONTEXT)\\\n";
		
		$line = fgets($infile);
		
		while($parenBalance > 0){
			
			$linedata = explode(" ", trim($line));
			
			//Special token sinalizing CONTEXT information
			if($linedata[0] == "//###"){
				$line = "    CONTEXT\\\n";
			}
			else{
				$line = rtrim($line);
				$line .= "\\\n";	
			}
		
			//eliminate comments
			if(strstr($line, "//")){
				//echo "comment: ", $line, "\n";
				$line = "\\\n";		
			}
			
			//eliminate any additional precompiler directives
			if(strstr($line, "#")){
				//echo "comment: ", $line, "\n";
				$line = "\\\n";		
			}			
			
			$output .= $line;
			
			$line = fgets($infile);
			
			if(strstr($line, "{"))
				$parenBalance++;
			
			if(strstr($line, "}"))
				$parenBalance--;			
			
		}
		
		return $output;
		
	}

    $_6502File = fopen("6502.pp", "r");
    
    $output = "";

	//Copy necessary functions
    while(($line = fgets($_6502File))){
        
        $linedata = explode(" ", $line);
        
        if($linedata[0] == "//^^^"){
			$output = Functions($_6502File);
			echo $output, "\n\n";
		}
        
    }
    
    rewind($_6502File);
    
    //At last, generate macros for the instruction functions
    while(($line = fgets($_6502File))){
        
        $linedata = explode(" ", $line);
        
        if($linedata[0] == "//%%%"){
			$output = InstructionMacro($_6502File);
			echo $output, "\n\n";
		}
        
    }
    
    fclose($_6502File);

?>
